<template>
	<div class="video_player" ref="video"></div>
</template>

<script>
export default {
	name: 'videoPlayer',
	props: {
		fileSrc: { type: String, default: '' },
		data: { type: Object, default: () => {} },
		timeUpdate: Function,
		playStart: Function,
		playEnd: Function
	},
	data() {
		return {
			videoPlayer: null,
			playTime: 0
		};
	},
	computed: {
		videoTime() {
			return this.$route.query.time;
		},
		isTryLook() {
			return !!this.$listeners['tryLookEnd'];
		},
		playerOption() {
			let options = { container: '.video_player', volume: 0.5 };
			options['autoplay'] = false;
			options['plug'] = 'hls.js';
			options['menu'] = [
				{ title: '播放/暂停', click: 'player.playOrPause' },
				{ title: '关于视频', click: 'aboutShow' }
			];
			options['timeScheduleAdjust'] = 1;
			options['video'] = [[this.fileSrc, '', '720', 0]];
			options['playbackrateList'] = [0.75, 1, 1.25, 1.5, 2];
			if (this.isTryLook) {
				options['timeScheduleAdjust'] = 0;
				options['prompt'] = [{ words: '试看结束', time: 120 }];
			}
			return options;
		}
	},
	watch: {
		playerOption: {
			handler(data) {
				if (!data) return false;
				this.$nextTick(() => {
					this.videoPlayer = this.initializePlayer();
				});
			},
			deep: true,
			immediate: true
		},
		playTime(time) {
			this.timeUpdate(time);
		}
	},
	methods: {
		initializePlayer() {
			let player = new ckplayer(this.playerOption);
			player.time((t) => {
				this.playTime = Math.round(t);
				if (!!this.$listeners['tryLookEnd']) {
					if (t < 120) return false;
					this.$emit('tryLookEnd', true);
					player.pause();
				}
			});
			player.play(() => {
				this.playStart(player);
			});
			player.ended(() => {
				this.playEnd(player.time());
			});
			this.$nextTick(() => {
				player.definition(0);
				if (!!this.videoTime) {
					player.seek(parseInt(this.videoTime));
				}
			});
			return player;
		}
	}
};
</script>

<style lang="scss" scoped>
.video_player {
	width: 100%;
	height: 100%;
}
</style>
